/***************************************
* @update: 2021-04-21   LiLinBin  [创建文件,编写功能]
* @update: 2021-04-26   LiLinBin  [增加组件分类,更改了commComps的数据结构]
* @update: 2021-06-17   LiLinBin  [根据配置文件,调整commComps的数据结构]
* @update: 2021-06-25   LiLinBin  [将组件文件的命名统一为"index.vue",缩略图统一命名为"[组件名].jpeg"]
* @update: 2021-06-28   LiLinBin  [每个组件提供width,height,方便组件调试时使用]
* @update: 2021-07-13   LiLinBin  [去掉每个组件提供的shape字段,将width,height直接挂载到ctrl]
* @update: 2021-07-13   LiLinBin  [将图片路径修改为服务器上的图片地址]
* @update: 2021-08-18   LiLinBin  [增加按需加载项目]
* @update: 2021-08-19   LiLinBin  [按需build项目,此文件的权限改为:只有林彬可以提交此文件的修改]
* @update: 2022-07-21   LiLinBin  [取消imgSrc给初始值,变更为在vEditor中读取缩略图路径]
* @update: 2022-07-21   LiLinBin  [path修改为全路径]
* @update: 2023-03-09   LiLinBin  [修改为:在VCloud中统一导入资源]
*
* @description: 读取所有的组件
*
* 组件信息对象
compInfo = {
    componentId: 'xx',      //组件的id
    componentName: 'xx',    //组件的名称
    vm: {},                 //组件对象
    path: 'xx',             //组件文件所在的路径
    imgSrc: 'xx',           //缩略图地址
    des: vm.des || '',    //备注说明
    width, 组件的宽,便于调试
    height 组件的高,便于调试
}
 ***************************************/

// 打包时不会引入以下导入的资源,在VCloud中统一导入
import eventConfigMixin from 'tools/mixins/2_eventConfigMixin.umd.min'
import changeDataConfigMixin from 'tools/mixins/4_changeDataConfigMixin'


const { baseConfig, buildProjects, buildInfo } = process.env
const { buildCommon, cutCommonComp } = baseConfig  //'old'旧版, 'new'新版
const hasCommon = buildProjects.includes("common")


const { default: interactMixin } = hasCommon && require('projects/common/mixin/interactMixin') || {}



//打包"common"时，选择需要去掉哪个版本的组件
const { hiderCompCfg } = hasCommon && require('../../comp.config.js') || {}
const {
    hiders: commonHiders = []
} = hiderCompCfg?.find(o => o.name === cutCommonComp) || {}




let commComps = [] //平台组件配置
let prjConfig = [] //项目配置




const init = () => {
    readPrjConfig()
    readFile()
}



const consoleWarn = (path) => {
    console.log('\n');
    console.warn('提示:每个组件必须要有组件名称.\n' + path)
    console.log('\n');
}



//读取项目配置
const readPrjConfig = () => {
    const prjConfigFilesArr = [
		require.context('../../../ProjectFrame/projects/培训测试项目', false, /prj.config.js$/)
	]

    prjConfigFilesArr.forEach((prjConfigFiles, index) => {
        // const prjName = prjConfigFiles.prototype.constructor.id.match(/projects\/(\S+)/)[1]
        const prjName = buildProjects[index]

        prjConfigFiles.keys().forEach(path => {
            const configFn = prjConfigFiles(path).default
            const configObj = configFn()

            if (prjName === "common") {
                commComps = configObj
            } else {
                prjConfig.push(configObj)
            }
        })
    })
}



/**
 * 1.以components下的文件夹名称为一级分类
 * 2.一级分类下的文件夹名称为二级分类
 * 3.二级分类下的文件为单个组件
 * 
 * 例: '/text/imgText/aqsjComp/index.vue': 'text'为一级分类,'imgText'为二级分类,'aqsjComp'的名称为组件名
 */
const readFile = () => {
    const projectCompsArr = [
		require.context('../../../ProjectFrame/projects/培训测试项目', true, /[(attr)|(index)].vue$/)
	]

	projectCompsArr.forEach((projectComps, index) => {
        // const prjName = projectComps.prototype.constructor.id.match(/projects\/(\S+)/)[1]
        const prjName = buildProjects[index]
        getCompInfo(projectComps, prjName)
    })
}



const getCompInfo = (compCtx, prjName) => {
    let allCommonNames = []
    const isCommonPrj = prjName === "common"

    compCtx.keys().forEach(path => {
        const isAttrComp = path.slice(-9) === "/attr.vue"
        const isIndexComp = path.slice(-10) === "/index.vue"

        if (!isAttrComp && !isIndexComp) return

        //组件所在的全路径
        const compPath = `ProjectFrame/projects/${prjName}${path.slice(1)}`

        try {
            const compModule = compCtx(path)
            const vm = compModule.default || compModule

            if (!vm.name) {
                consoleWarn(compPath)
                return
            }

            //组件的name字段
            if (isCommonPrj && buildCommon === 'new') {
                const originName = vm.name
                vm.name = 'vtron' + originName[0].toUpperCase() + originName.slice(1)

                const compName = vm.name
                const cutAttrName = compName.replace(/Attr$/, '')

                if (commonHiders.find(o => o.componentName == compName)) return
                if (commonHiders.find(o => o.componentName == cutAttrName)) return
            }

            const vmName = vm.name
            const desNameMixin = {
                data: () => ({
                    desName: `${vm.des}-${vmName}`,
                    compPath: compPath
                })
            }

            const symbol = path.includes('\\') ? "\\" : "\/"
            const arr = path.split(symbol)

            const firstType = isCommonPrj ? arr[1] : prjName  //一级分类
            const secondType = isCommonPrj ? arr[2] : arr[1] //二级分类

            //排除配置组件
            if (isIndexComp) {
                const addMixins = [changeDataConfigMixin, eventConfigMixin, desNameMixin]
                Array.isArray(vm.mixins)
                    ? vm.mixins.unshift(...addMixins)
                    : vm.mixins = addMixins
            } else {
                Array.isArray(vm.mixins)
                    ? vm.mixins.unshift(desNameMixin)
                    : vm.mixins = [desNameMixin]
            }

            if (isCommonPrj && isIndexComp) vm.mixins.unshift(interactMixin)

            const vmData = (vm.data && vm.data()) || {}
            const devInfo = vm.devInfo || {}

            const compInfo = {
                componentId: 'comp-' + T.uuid(),
                componentName: vmName,
                vm: vm,
                path: compPath,
                imgSrc: "",                 //在vEditor中赋值
                des: vm.des || '',        //备注说明
                devInfo: {                  //组件的开发信息记录: '作者''版本''更新记录'
                    '作者': devInfo['作者'] || '',
                    '时间': devInfo['时间'] || '',
                    '版本': devInfo['版本'] || 'v1.0',
                    '更新记录': (devInfo['更新记录'] || []).map((str, num) => `${num + 1}、${str}`).join('；') + '。'
                },
                width: vmData.width || '200px',
                height: vmData.height || '200px',
                left: vmData.left || '0px',
                top: vmData.top || '0px'
            }

            const config = isCommonPrj ? commComps : prjConfig

            //查找一级分类
            const oneIndex = config.findIndex(o => o.value === firstType)
            if (oneIndex < 0) return

            //查找二级分类
            const twoIndex = config[oneIndex].children.findIndex(o => o.value === secondType)
            if (twoIndex < 0) return

            config[oneIndex].children[twoIndex].children.push(compInfo)

            //调试使用
            /* if (isCommonPrj && isIndexComp) {
                allCommonNames.push({
                    componentName: vmName,
                    des: vm.des || '',
                    path: compPath,
                    basicHide: false,
                    superHide: false
                })
            } */
        } catch (error) {
            console.error("组件编译错误:" + path);
            console.error(error);
        }
    })

    // console.log('00000', allCommonNames);
}




init()






export {
    commComps,
    prjConfig,
    buildInfo
}